﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.ReflectionModel;
using System.Linq;
using Caliburn.Micro;

namespace OrbitOne.CRMLyncInfoDashboard.Loader
{
    public class LoadCatalog : IResult
    {
        private readonly Dictionary<string, DeploymentCatalog> Catalogs = new Dictionary<string, DeploymentCatalog>();
        private readonly string m_uri;

        [Import]
        public AggregateCatalog Catalog { get; set; }

        public LoadCatalog(string relativeUri)
        {
            m_uri = relativeUri;
        }

        public void Execute(ActionExecutionContext context)
        {
            DeploymentCatalog catalog;

            if (Catalogs.TryGetValue(m_uri, out catalog))
            {
                Completed(this, new ResultCompletionEventArgs());
            }
            else
            {
                catalog = new DeploymentCatalog(m_uri);
                catalog.DownloadCompleted += (s, e) =>
                                                 {
                                                     if (e.Error == null)
                                                     {
                                                         Catalogs[m_uri] = catalog;
                                                         Catalog.Catalogs.Add(catalog);
                                                         catalog.Parts
                                                             .Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly)
                                                             .Where(assembly => !AssemblySource.Instance.Contains(assembly))
                                                             .Apply(x => AssemblySource.Instance.Add(x));
                                                     }
                                                     Completed(this, new ResultCompletionEventArgs
                                                                         {
                                                                             Error = e.Error,
                                                                             WasCancelled = false
                                                                         });
                                                 };
                catalog.DownloadAsync();
            }
        }

        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
    }
}